package com.ai.aicodemather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ai.aicodemather.exception.BusinessException;
import com.ai.aicodemather.exception.ErrorCode;
import com.ai.aicodemather.model.dto.UserQueryRequest;
import com.ai.aicodemather.model.enums.UerRoleTypeEnum;
import com.ai.aicodemather.model.vo.UserLoginResponseVo;
import com.ai.aicodemather.model.vo.UserVO;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ai.aicodemather.model.entity.User;
import com.ai.aicodemather.mapper.UserMapper;
import com.ai.aicodemather.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ai.aicodemather.constant.UserConstant.USER_LOGIN_STATE;

/**
 *  服务层实现。
 *
 * @author aiCodeMather
 * @since 2023-03-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    /**
     * 用户注册
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public long registerUser(String userAccount, String userPassword, String checkPassword) {
        // 1. 参数校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空！");
        }
        if (userPassword.length() < 8 ||checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于8位！");
        }
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致！");
        }
        // 2. 检查用户名是否已存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userName", userAccount);
        long count = this.mapper.selectCountByQuery(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在！");
        }
        // 3. 账号加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 保存用户信息
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(userAccount);
        user.setUserRole(UerRoleTypeEnum.USER.getValue());
        boolean insert = this.save(user);
        if (!insert){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败,数据库错误！");
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount
     * @param userPassword
     * @param httpRequest
     * @return
     */
    @Override
    public UserLoginResponseVo userLogin(String userAccount, String userPassword, HttpServletRequest httpRequest) {
        // 1. 参数校验
        if (StrUtil.hasBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空！");
        }
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于8位！");
        }
        // 2. 密码加密
        String encryptPassword = getEncryptPassword(userPassword);

        // 3. 检查用户名,密码是否存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userName", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.mapper.selectOneByQuery(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码错误！");
        }
        // 4. 保存用户信息到session中
        httpRequest.getSession().setAttribute(USER_LOGIN_STATE, user);
        // 5. 返回用户信息,脱敏后的
        return this.getUserLoginResponseVo(user);
    }

    /**
     * 获取当前登录用户信息
     * @param httpRequest
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest httpRequest) {
        // 从session中获取用户信息
        User user = (User) httpRequest.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库中查询数据库
        user = this.mapper.selectOneById(user.getId());
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }

    /**
     * 获取当前登录用户信息
     * @param httpRequest
     * @return
     */
    @Override
    public UserLoginResponseVo getLoginUserVo(HttpServletRequest httpRequest) {
        return  this.getUserLoginResponseVo(this.getLoginUser(httpRequest));
    }

    /**
     * 用户登出
     * @param httpRequest
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest httpRequest) {
        // 判断用户是否登录
        User user = (User) httpRequest.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 清除session中的用户信息
        httpRequest.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }


    /**
     * 密码加密
     * @param userPassword
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "ai-code";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 将User对象转换为UserLoginResponseVo对象,用户信息脱敏
     * @param user
     * @return
     */
    @Override
    public UserLoginResponseVo getUserLoginResponseVo(User user){
        if (user == null){
            return null;
        }
        UserLoginResponseVo userLoginResponseVo = new UserLoginResponseVo();
        BeanUtil.copyProperties(user, userLoginResponseVo);
        return userLoginResponseVo;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        return QueryWrapper.create()
                .eq("id", id)
                .eq("userRole", userRole)
                .like("userAccount", userAccount)
                .like("userName", userName)
                .like("userProfile", userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }


}
